package com.etboot.modules.base.serviceimpl;

import com.etboot.common.constant.CommonConstant;
import com.etboot.modules.base.dao.UserDao;
import com.etboot.modules.base.dao.UserRoleDao;
import com.etboot.modules.base.dao.mapper.UserMapper;
import com.etboot.modules.base.entity.User;
import com.etboot.modules.base.entity.UserRole;
import com.etboot.modules.base.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户角色接口实现
 *
 * @author Exrickx
 */
@Slf4j
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleDao userRoleDao;
    // @Autowired
    // private UserDao userDao;
    @Autowired
    private UserMapper userMapper;

    // @PersistenceContext
    // private EntityManager entityManager;

    @Override
    public UserRoleDao getRepository() {
        return userRoleDao;
    }

    @Override
    public List<UserRole> findByRoleId(String roleId) {
        return userRoleDao.findByRoleId(roleId);
    }

    /**
     * 供 Activiti 使用，根据角色查询所含的用户
     */
    @Override
    public List<User> findUserByRoleId(String roleId) {
        List<UserRole> userRoleList = findByRoleId(roleId);
        List<User> list = new ArrayList<>();
        for (UserRole ur : userRoleList) {
            User u = userMapper.selectById(ur.getUserId());
            // User u = userDao.getOne(ur.getUserId());
            if (u != null && CommonConstant.USER_STATUS_NORMAL.equals(u.getStatus())) {
                list.add(u);
            }
            // entityManager.detach(u);
        }
        // fix bug: 取消 set 对象字段时，hibernate 自动更新对象
        // 方式一 清除持久上下文环境 避免后面语句导致持久化
        // entityManager.clear();
        // 方式二 使Session中的该对象变为游离态
        // entityManager.detach(u);
        return list;
    }

    @Override
    public void deleteByUserId(String userId) {
        userRoleDao.deleteByUserId(userId);
    }
}
